(function () {
    function $(select) {
        return document.querySelector(select)
    }

    function $$(select) {
        return document.querySelectorAll(select)
    }

    var midImg = $('.left-img'),
        bigImg = $('.right-img'),
        maskDom = $('.mask'),
        imgList = $('.img-list');
    
    var imgObj = {
        small: ['imgA_1.jpg', 'imgB_1.jpg', 'imgC_1.jpg'],
        mid: ['imgA_2.jpg', 'imgB_2.jpg', 'imgC_2.jpg'],
        big: ['imgA_3.jpg', 'imgB_3.jpg', 'imgC_3.jpg']
    }

    // 初始化
    var str = ''
    for (var i = 0; i < imgObj.small.length; i++){
        str += `<li style='background-image:url(./images/${imgObj.small[i]})'></li>`
    }
    imgList.innerHTML = str
     
    $('.img-list li').style.border = '1px solid #000'

    // 点击事件
    imgList.onclick =  function (e) {
        // console.log(e.target.tagName);
        if (e.target.tagName === 'LI') {
            var lis = $$('.img-list li')
            for (var i = 0; i < lis.length; i++){
                lis[i].style.border = 'none'
            }
            var index = [].indexOf.call(lis,e.target)
            lis[index].style.border = '1px solid #000'

            midImg.style.backgroundImage = `url(./images/${imgObj.mid[index]})`
            bigImg.style.backgroundImage = `url(./images/${imgObj.big[index]})`
        }
    }



    // 鼠标移入
    midImg.onmousemove = function (e) {
    //    e.clientX 鼠标到页面左边的距离
    //    e.clientY 鼠标到页面上边的距离
        
        maskDom.style.opacity = 1
        bigImg.style.opacity = 1
        var left = e.clientX - midImg.offsetLeft - maskDom.offsetWidth / 2
        var top = e.clientY - midImg.offsetTop - maskDom.offsetHeight / 2
        
        if (left <= 0) {
            left = 0
        }
        if (top <= 0) {
            top = 0
        }
        if (left >= midImg.offsetWidth - maskDom.offsetWidth) {
            left = midImg.offsetWidth - maskDom.offsetWidth
        }
        if (top >= midImg.offsetHeight - maskDom.offsetHeight) {
            top = midImg.offsetHeight - maskDom.offsetHeight
        }

        bigImg.style.backgroundPositionX = - left + 'px'
        bigImg.style.backgroundPositionY = -top + 'px'

        maskDom.style.top = top + 'px'
        maskDom.style.left = left + 'px'
    }

    // 移出
    midImg.onmouseleave = function (e) {
        maskDom.style.opacity = 0
        bigImg.style.opacity = 0
    }

})()